/*
 * @(#)MailManager.java
 * 2014-1-7 下午11:41:13
 * 
 *
 * Copyright (c) 2018-2028, HangZhou QiYun InfoTech Co.,Ltd. .
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.qyxx.platform.sysmng.msg.service;

import java.util.Date;
import java.util.List;

import javax.mail.MessagingException;
import javax.mail.internet.AddressException;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.qyxx.platform.common.orm.Page;
import com.qyxx.platform.common.orm.PropertyFilter;
import com.qyxx.platform.common.utils.ExceptionUtils;
import com.qyxx.platform.sysmng.accountmng.dao.UserDao;
import com.qyxx.platform.sysmng.accountmng.entity.User;
import com.qyxx.platform.sysmng.msg.dao.SendMailMsgDao;
import com.qyxx.platform.sysmng.msg.entity.SendMailMsg;


/**
 *  邮件服务类
 *  @author gxj
 *  @version 1.0 2014-1-7 下午11:41:13
 *  @since jdk1.6 
 */
@Component
@Transactional
public class MailManager {
	
	private static Logger logger = LoggerFactory.getLogger(MailManager.class);
	
	private SendMailMsgDao sendMailMsgDao;

	private User user;
	
	private UserDao userDao;

	/**
	 * @param userDao
	 */
	@Autowired
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}
	
	/**
	 * @param sendMailMsgDao
	 */
	@Autowired
	public void setSendMailMsgDao(SendMailMsgDao sendMailMsgDao) {
		this.sendMailMsgDao = sendMailMsgDao;
	}
	
	public void setUser(User user) {
		this.user = user;
	}
	
	/**
	 * 发送邮件方法
	 * 
	 * @param smm
	 */
	public void sendMail(SendMailMsg smm) {
		//smm.setCreateTime(new Date());
		String[] rps =  StringUtils.split(smm.getAddressee(), ";");
		String[] cc = StringUtils.split(smm.getCopyto(), ";");
		String[] bcc = StringUtils.split(smm.getBcc(), ";");
		try {
			smm.setSendTime(new Date());
			MailFactory.getServiceMail(smm.getServiceMail()).send(rps, smm.getSubject(), smm.getMailBody(), cc, bcc);
			smm.setStatus(SendMailMsg.STATUS_SEND);
		} catch (AddressException e) {
			logger.error("邮件【" + smm.getSubject() + "】地址存在问题，导致发送失败", e);
			smm.setResult(ExceptionUtils.getStackTrace(e));
		} catch (MessagingException e) {
			logger.error("邮件【" + smm.getSubject() + "】信息存在问题，导致发送失败", e);
			smm.setResult(ExceptionUtils.getStackTrace(e));
		} catch (Exception e) {
			logger.error("邮件【" + smm.getSubject() + "】发送存在问题，导致发送失败", e);
			smm.setResult(ExceptionUtils.getStackTrace(e));
		} finally {
			sendMailMsgDao.save(smm);
		}
	}
	
	/**
	 * 发送所有待发送邮件
	 */
	public void sendAllMails() {
		List<SendMailMsg> smmList = sendMailMsgDao.findBy("status", SendMailMsg.STATUS_UNSEND);
		if(smmList != null) {
			for(SendMailMsg smm : smmList) {
				sendMail(smm);
			}
		}
	}
	
	/**
	 * 分页查询数据列表
	 * 使用属性过滤条件查询日志
	 */
	@Transactional(readOnly = true)
	public Page<SendMailMsg> queryList(final Page<SendMailMsg> page, final List<PropertyFilter> filters) {
		return preHandlePage(sendMailMsgDao.findPage(page, filters));
	}

	/**
	 * 获取单条数据对象
	 * 
	 * @param id
	 * @return
	 */
	@Transactional(readOnly = true)
	public SendMailMsg get(Long id) {
		return sendMailMsgDao.get(id);
	}
	
	/**
	 * 保存数据
	 * 
	 * @param entity
	 */
	public void save(SendMailMsg entity) {
		Long id = entity.getId();
		if(id==null) {
			entity.setCreateUser(user.getId());
			entity.setCreateTime(new Date());
		} else {
			entity.setLastUpdateUser(user.getId());
			entity.setLastUpdateTime(new Date());
		}
		sendMailMsgDao.save(entity);
	}
	
	/**
	 * 更新附件字段
	 * 
	 * @param id
	 * @param atmId
	 */
	public void updateAttach(Long id, Long atmId) {
		SendMailMsg smm = sendMailMsgDao.get(id);
		smm.setAtmId(atmId);
	}
	
	/**
	 * 更新状态
	 * 
	 * @param id
	 * @param status
	 */
	public void updateStatus(Long id, String status) {
		SendMailMsg smm = sendMailMsgDao.get(id);
		smm.setStatus(status);
		smm.setLastUpdateTime(new Date());
		smm.setLastUpdateUser(user.getId());
	}
	
	/**
	 * 批量删除数据
	 * 
	 * @param ids
	 */
	public void delete(Long[] ids) {
		if(null!=ids) {
			for(Long id : ids) {
				sendMailMsgDao.delete(id);
			}
		}
	}
	
	/**
	 * 处理Page对象，翻译字段
	 * 
	 * @param page
	 * @return
	 */
	public Page<SendMailMsg> preHandlePage(Page<SendMailMsg> page) {
		List<SendMailMsg> list = page.getResult();
		if(list != null) {
			for(SendMailMsg n : list) {
				n.setCreateUserCaption(userDao.getUserNameById(n.getCreateUser()));
			}
		}
		return page;
	}
	
}
